package com.dengpp.pdform.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.dengpp.pdform.R;
import com.dengpp.pdform.model.MediaFile;
import com.dengpp.pdform.view.ImagePreviewActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MediaAdapter extends RecyclerView.Adapter<MediaAdapter.MediaViewHolder> {

    private List<MediaFile> mediaFiles;
    private OnRemoveListener removeListener;
    private boolean isEditMode;
    private int spanCount = 3; // 默认3列


    public MediaAdapter() {
        this.mediaFiles = new ArrayList<>();
    }

    public void setMediaFiles(List<MediaFile> mediaFiles) {
        this.mediaFiles = mediaFiles != null ? mediaFiles : new ArrayList<>();
        notifyDataSetChanged();
    }

    public void setEditMode(boolean editMode) {
        this.isEditMode = editMode;
        notifyDataSetChanged();
    }

    public void setSpanCount(int spanCount) {
        this.spanCount = spanCount;
        notifyDataSetChanged();
    }


    public void setOnRemoveListener(OnRemoveListener listener) {
        this.removeListener = listener;
    }

    @NonNull
    @Override
    public MediaViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.library_item_media, parent, false);
        return new MediaViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MediaViewHolder holder, int position) {
        holder.bind(mediaFiles.get(position), isEditMode, removeListener, spanCount);
    }

    @Override
    public int getItemCount() {
        return mediaFiles.size();
    }

    public interface OnRemoveListener {
        void onRemove(int position, MediaFile mediaFile);
    }

    static class MediaViewHolder extends RecyclerView.ViewHolder {

        private String TAG = "MediaViewHolder";
        private ImageView imageView;
        private ImageView ivPlay;
        private ImageView ivRemove;
        private FrameLayout frameLayout;

        public MediaViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.iv_media);
            ivPlay = itemView.findViewById(R.id.iv_play);
            ivRemove = itemView.findViewById(R.id.iv_remove);
            frameLayout = itemView.findViewById(R.id.frame_layout);
        }

        public void bind(MediaFile mediaFile, boolean isEditMode, OnRemoveListener removeListener, int spanCount) {

            // 根据列数动态调整item高度
            adjustItemSize(spanCount);

            // 使用Glide加载图片
            Context context = itemView.getContext();
            if (mediaFile.getType() == MediaFile.MediaType.IMAGE) {
                Glide.with(context)
                        .load(mediaFile.getPath())
                        .placeholder(R.drawable.library_ic_image_placeholder)
                        .into(imageView);
                ivPlay.setVisibility(View.GONE);
            } else {
                // 加载视频缩略图
                String thumbnail = mediaFile.getThumbnail() != null ?
                        mediaFile.getThumbnail() : mediaFile.getPath();
                Glide.with(context)
                        .load(thumbnail)
                        .placeholder(R.drawable.library_ic_video_placeholder)
                        .into(imageView);
                ivPlay.setVisibility(View.VISIBLE);
            }

            // 显示位置信息
            if (mediaFile.getLocationInfo() != null) {
                // 可以在图片上添加位置标记或提示
                itemView.setContentDescription("包含位置信息的图片: " + mediaFile.getLocationInfo().toString());
            }

            if (isEditMode) {
                ivRemove.setVisibility(View.VISIBLE);
                ivRemove.setOnClickListener(v -> {
                    // 显示确认删除对话框
                    showDeleteConfirmationDialog(context, getAdapterPosition(), mediaFile, removeListener);
//                    if (removeListener != null) {
//                        removeListener.onRemove(getAdapterPosition(), mediaFile);
//                    }
                });
            } else {
                ivRemove.setVisibility(View.GONE);
            }

            itemView.setOnClickListener(v -> {
                previewMedia(mediaFile);
            });
        }



        /**
         * 显示确认删除对话框（Material Design 风格）
         */
        private void showDeleteConfirmationDialog(Context context, int position, MediaFile mediaFile, OnRemoveListener removeListener) {
            // 创建自定义对话框布局
            View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_delete_confirmation, null);

            TextView tvMessage = dialogView.findViewById(R.id.tv_message);
            Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
            Button btnDelete = dialogView.findViewById(R.id.btn_delete);

            // 设置提示信息
            String message = mediaFile.getType() == MediaFile.MediaType.IMAGE ?
                    "确定要删除这张图片吗？" : "确定要删除这个视频吗？";
            tvMessage.setText(message);

            // 创建对话框
            androidx.appcompat.app.AlertDialog dialog = new androidx.appcompat.app.AlertDialog.Builder(context)
                    .setView(dialogView)
                    .setCancelable(true)
                    .create();

            // 设置按钮点击事件
            btnCancel.setOnClickListener(v -> dialog.dismiss());
            btnDelete.setOnClickListener(v -> {
                if (removeListener != null) {
                    removeListener.onRemove(position, mediaFile);
                }
                dialog.dismiss();
            });

            dialog.show();
        }

        private void adjustItemSize(int spanCount) {
            ViewGroup.LayoutParams layoutParams = frameLayout.getLayoutParams();

            if (spanCount == 1) {
                // 1列时：占满宽度，设置合适的高度
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutParams.height = (int) (250 * itemView.getContext().getResources().getDisplayMetrics().density);
                frameLayout.setLayoutParams(layoutParams);
            }
        }

        private void previewMedia(MediaFile mediaFile) {
            Context context = itemView.getContext();

            if (mediaFile.getType() == MediaFile.MediaType.VIDEO) {
                // 视频预览
                previewVideo(context, mediaFile);
            } else {
                // 图片预览
                previewImage(context, mediaFile);
            }
        }

        private void previewImage(Context context, MediaFile mediaFile) {
            try {
                Uri imageUri = getMediaUri(mediaFile);
                if (imageUri != null) {
                    // 使用自定义图片预览Activity
                    Intent intent = new Intent(context, ImagePreviewActivity.class);
                    intent.putExtra("image_uri", imageUri.toString());
                    intent.putExtra("image_title", mediaFile.getName() != null ? mediaFile.getName() : "图片预览");
                    context.startActivity(intent);
                } else {
                    Toast.makeText(context, "无法预览图片", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Log.e(TAG, "图片预览失败", e);
                Toast.makeText(context, "图片预览失败", Toast.LENGTH_SHORT).show();
            }
        }

        private void previewVideo(Context context, MediaFile mediaFile) {
            try {
                Uri videoUri = getMediaUri(mediaFile);
                if (videoUri != null) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(videoUri, "video/*");
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                    // 检查是否有应用可以处理视频
                    if (intent.resolveActivity(context.getPackageManager()) != null) {
                        context.startActivity(intent);
                    } else {
                        Toast.makeText(context, "没有找到可用的视频播放器", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(context, "无法播放视频", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Log.e(TAG, "视频播放失败", e);
                Toast.makeText(context, "视频播放失败", Toast.LENGTH_SHORT).show();
            }
        }

        private Uri getMediaUri(MediaFile mediaFile) {
            try {
                String path = mediaFile.getPath();
                if (path.startsWith("content://")) {
                    // 如果是content URI，直接使用
                    return Uri.parse(path);
                } else if (path.startsWith("file://")) {
                    // 如果是file URI，转换为content URI
                    File file = new File(path.substring(7));
                    return FileProvider.getUriForFile(itemView.getContext(),
                            itemView.getContext().getPackageName() + ".fileprovider", file);
                } else {
                    // 如果是普通路径
                    File file = new File(path);
                    if (file.exists()) {
                        return FileProvider.getUriForFile(itemView.getContext(),
                                itemView.getContext().getPackageName() + ".fileprovider", file);
                    } else {
                        // 如果文件不存在，尝试作为网络URL处理
                        return Uri.parse(path);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "获取媒体URI失败", e);
                return null;
            }
        }
    }
}
